package com.example.cshaoshao.demo.activities;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.example.cshaoshao.demo.R;
import com.example.cshaoshao.demo.fragments.FragmentOne;
import com.example.cshaoshao.demo.fragments.FragmentThree;
import com.example.cshaoshao.demo.fragments.FragmentTwo;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by cshaoshao on 2017/6/30.
 */

public class StyleActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {
    @BindView(R.id.rg)
    RadioGroup rg;
    FragmentOne fragmentOne;
    FragmentTwo fragmentTwo;
    FragmentThree fragmentThree;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_style);
        ButterKnife.bind(this);
        rg.setOnCheckedChangeListener(this);
        RadioButton childAt= (RadioButton) rg.getChildAt(0);
        childAt.setChecked(true);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
        hideAllFragment(transaction);
        switch (checkedId)
        {
            case R.id.index :
                if(fragmentOne==null)
                {
                    fragmentOne=FragmentOne.getInstance();
                    transaction.add(R.id.fl,fragmentOne);
                }
                else
                {
                    transaction.show(fragmentOne);
                }
                break;
            case R.id.video :
                if(fragmentTwo==null)
                {
                    fragmentTwo=FragmentTwo.getInstance();
                    transaction.add(R.id.fl,fragmentTwo);
                }
                else
                {
                    transaction.show(fragmentTwo);
                }
                break;
            case R.id.mine :
                if(fragmentThree==null)
                {
                    fragmentThree=FragmentThree.getInstance();
                    transaction.add(R.id.fl,fragmentThree);
                }
                else
                {
                    transaction.show(fragmentThree);
                }
                break;
            default:
                break;
        }
        transaction.commit();
    }

    private void hideAllFragment(FragmentTransaction transaction) {
        if(transaction==null)
        {
            return;
        }
       if(fragmentOne!=null)
        {
            transaction.hide(fragmentOne);
        }
        if(fragmentTwo!=null)
        {
            transaction.hide(fragmentTwo);
        }
        if(fragmentThree!=null)
        {
            transaction.hide(fragmentThree);
        }
    }
}
